package Day2025_03_08;

public class LeetCode130 {
    public void solve(char[][] board) {
        int m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O') bfs(board, i, 0, '*', 'O');
            if (board[i][n - 1] == 'O') bfs(board, i, n - 1, '*', 'O');
        }
        for (int i = 0; i < n; i++) {
            if (board[0][i] == 'O') bfs(board, 0, i, '*', 'O');
            if (board[m - 1][i] == 'O') bfs(board, m - 1, i, '*', 'O');
        }
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                if (board[i][j] == 'O') bfs(board, i , j, 'X', 'O');
            }
        }
        for (int i = 0; i < m; i++) {
            if (board[i][0] == '*') bfs(board, i, 0, 'O', '*');
            if (board[i][n - 1] == '*') bfs(board, i, n - 1, 'O', '*');
        }
        for (int i = 0; i < n; i++) {
            if (board[0][i] == '*') bfs(board, 0, i, 'O', '*');
            if (board[m - 1][i] == '*') bfs(board, m - 1, i, 'O', '*');
        }
    }
    private void bfs (char[][] board, int i, int j, char ch1, char ch2) {
        int m = board.length, n = board[0].length;
        if (i >= 0 && i < m && j >= 0 && j < n && board[i][j] == ch2) {
            board[i][j] = ch1;
            bfs(board, i - 1, j, ch1, ch2);
            bfs(board, i + 1, j, ch1, ch2);
            bfs(board, i, j - 1, ch1, ch2);
            bfs(board, i, j + 1, ch1, ch2);
        }
    }

    public void solve2(char[][] board) {
        int m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O') bfs(board, i, 0);
            if (board[i][n - 1] == 'O') bfs(board, i, n - 1);
        }
        for (int i = 0; i < n; i++) {
            if (board[0][i] == 'O') bfs(board, 0, i);
            if (board[m - 1][i] == 'O') bfs(board, m - 1, i);
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O') board[i][j] = 'X';
                if (board[i][j] == '*') board[i][j] = 'O';
            }
        }
    }
    private void bfs (char[][] board, int i, int j) {
        int m = board.length, n = board[0].length;
        if (i >= 0 && i < m && j >= 0 && j < n && board[i][j] == 'O') {
            board[i][j] = '*';
            bfs(board, i - 1, j);
            bfs(board, i + 1, j);
            bfs(board, i, j - 1);
            bfs(board, i, j + 1);
        }
    }
}
